import { BanditConfig, removeUnNeedCfg } from "@/components/config";
import { Button, Card, Space, Tabs } from "antd";
import { useState } from "react";
import { min_app_fs, min_app_shell } from '@linksaas-minapp/api';
import useForceUpdate from 'use-force-update';
import GlobalPanel from "@/components/GlobalPanel";
import RulePanel from "@/components/RulePanel";
import toml from "@iarna/toml";

export default function Home() {
  const forceUpdate = useForceUpdate();
  const [banditCfg, setBanditCfg] = useState<BanditConfig>({});

  const openFile = async () => {
    let files = await min_app_fs.readFile(
      false,
      "toml文件", ["toml"]
    );
    if (files.length == 0) {
      return;
    }
    try {
      const content = new TextDecoder("utf-8").decode(files[0].file_data);
      const cfg = toml.parse(content) as unknown as BanditConfig;
      setBanditCfg(cfg);
    } catch (e) {
      console.log(e);
    }
  };

  const saveFile = async () => {
    const tmpCfg = removeUnNeedCfg(banditCfg);
    const content = toml.stringify(tmpCfg as unknown as toml.JsonMap);
    const data = new TextEncoder().encode(content);
    await min_app_fs.writeFile("bandit.toml", data);
  }


  return (
    <Card title="bandit配置助手" extra={
      <Space>
        <Button type="link" onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          min_app_shell.openBrowser("https://bandit.readthedocs.io/");
        }}>官方网站</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          setBanditCfg({});
          forceUpdate();
        }}>清空配置</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          openFile();
        }}>导入</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          saveFile();
        }}>导出</Button>
      </Space>
    }>
      <Tabs defaultActiveKey="global">
        <Tabs.TabPane key="global" tab="全局配置">
          <GlobalPanel cfg={banditCfg.tool?.bandit ?? {}} onChange={cfg => {
            setBanditCfg({ tool: { bandit: cfg } });
            forceUpdate();
          }} />
        </Tabs.TabPane>
        <Tabs.TabPane key="detail" tab="规则详细设置">
          <RulePanel cfg={banditCfg.tool?.bandit ?? {}} onChange={cfg => {
            setBanditCfg({ tool: { bandit: cfg } });
            forceUpdate();
          }} />
        </Tabs.TabPane>
      </Tabs>
    </Card>
  )
}
